package cn.com.scooper.common.exception;

import cn.com.scooper.common.resp.APIObjectJson;
import cn.com.scooper.common.resp.ResultCode;
import cn.com.scooper.impl.xf.MineDeviceAlarmServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;


@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
	
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public APIObjectJson handleUnexpectedServerError(Exception ex) {
        logger.error(ex.toString());
        ex.printStackTrace();
        return new APIObjectJson(-1, ex.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(BusinessException.class)
    public APIObjectJson handleBusinessException(BusinessException ex) {
        return new APIObjectJson(ex.getCode(), ex.getMessage());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public APIObjectJson validationException(MethodArgumentNotValidException e) {

        String msg = e.getBindingResult().getFieldErrors()
                .stream()
                .map(n -> String.format("%s: %s", n.getField(), 		      n.getDefaultMessage()))
                .reduce((x, y) -> String.format("%s; %s", x, y))
                .orElse("参数输入有误");
        return new APIObjectJson(ResultCode.PARAM_ERR,msg);
    }
}

